package com.tim.app.ui.view;

import android.content.Context;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.util.TimeUtil;
import com.application.library.widget.roundimg.RoundedImageView;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.ActionStateMsg;
import com.tim.app.server.entry.Article;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.FollowResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.some_homepage.SomeoneHomepageActivity;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.TextUtil;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

/**
 * 文章详情的header
 */

public class ArticleHeadView extends RelativeLayout implements View.OnClickListener, LSWebView.OnOpenUrlListener {

    public static final String TAG = "ArticleHeadView";


    private LSWebView wbContent;

    private TextView tvArticleTitle;
    private TextView tvFollow;

    private RoundedImageView rivAvatar;
    private TextView tvUserName;
    private TextView tvContextTime;

    private Article article;

    private View icCommentContainer;

    public ArticleHeadView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        wbContent = (LSWebView) findViewById(R.id.wbContent);
        tvArticleTitle = (TextView) findViewById(R.id.tvArticleTitle);
        tvFollow = (TextView) findViewById(R.id.tvFollow);
        rivAvatar = (RoundedImageView) findViewById(R.id.rivAvatar);
        tvUserName = (TextView) findViewById(R.id.tvUserName);
        tvContextTime = (TextView) findViewById(R.id.tvContextTime);
        icCommentContainer = findViewById(R.id.icCommentContainer);

        tvFollow.setOnClickListener(this);
        rivAvatar.setOnClickListener(this);
        tvUserName.setOnClickListener(this);
        wbContent.setOnOpenUrlListener(this);
    }

    /**
     * 刷新页面
     *
     * @param data
     */
    public void setData(final Article data) {
        if (null == data)
            return;
        article = data;
        if (null != data.getUserMsg()) {
            if (!TextUtils.isEmpty(data.getUserMsg().getImage())) {
                BitmapLoader.ins().loadImage(data.getUserMsg().getImage(), rivAvatar);
            }
            if (!TextUtils.isEmpty(data.getUserMsg().getName())) {
                tvUserName.setText(data.getUserMsg().getName());
            }
            if (UserManager.ins().isLogin()) {
                if (data.getUserMsg().getUserId().equals(UserManager.ins().getUserId())) {
                    tvFollow.setVisibility(View.GONE);
                }
            }
        }
        if (null != data.getActionStateMsg()) {
            if (null != data.getActionStateMsg().getUserState()) {
                tvFollow.setSelected(true);
                tvFollow.setText(R.string.hasFollow);
            } else {
                tvFollow.setSelected(false);
                tvFollow.setText(R.string.unFollow);
            }
            tvContextTime.setText(getContext().getString(R.string.createTime, TimeUtil.formatTimeRuleTwo(getContext(), data.getCreateTime())));
        }
        if (!TextUtils.isEmpty(data.getTitle())) {
            tvArticleTitle.setText(String.valueOf(data.getTitle()));
        }
    }

    public void showContent(String url) {
        wbContent.openUrl(url);
    }

    @Override
    public void onOpenUrl(String url) {

    }

    @Override
    public void showLoadingLayout() {

    }

    @Override
    public void hideLoadingLayout() {
        tvContextTime.setVisibility(View.VISIBLE);
        icCommentContainer.setVisibility(View.VISIBLE);
    }

    @Override
    public void onReceivedError() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvFollow:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(getContext());
                    return;
                }
                followOrCancelFollow();
                break;
            case R.id.tvUserName:
            case R.id.rivAvatar:
                SomeoneHomepageActivity.start(getContext(), article.getUserMsg(), false);
                break;
        }
    }

    /**
     * 关注/取消关注
     */
    private void followOrCancelFollow() {
        tvFollow.setEnabled(false);
        if (null != article.getActionStateMsg() && article.getActionStateMsg().getUserState() != null) {
            int id = article.getActionStateMsg().getUserState();
            API_User.ins().cancelFollow(TAG, id, UserManager.ins().getUserId(), article.getUserMsg().getUserId(), AppKey.TYPE_USER, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    tvFollow.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        tvFollow.setSelected(false);
                        tvFollow.setText(R.string.unFollow);
                        article.getActionStateMsg().setUserState(null);
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        } else {
            API_User.ins().addFollow(TAG, UserManager.ins().getUserId(), article.getUserMsg().getUserId(), AppKey.TYPE_USER, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    tvFollow.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        FollowResult result = new Gson().fromJson(resultValue, FollowResult.class);
                        if (null != result && null != result.getRes()) {
                            if (article.getActionStateMsg() == null) {
                                article.setActionStateMsg(new ActionStateMsg());
                            }
                            article.getActionStateMsg().setUserState(result.getRes().getConcern().getId());
                            tvFollow.setSelected(true);
                            tvFollow.setText(R.string.hasFollow);
                        }
                    } else if (ResponseResult.ResultStatus.BE_ADD_BLACK == errCode) {
                        if (article.getUserMsg().getSex() == AppKey.SEX_MAN) {
                            ToastUtil.showToast("由于对方的设置，你不能关注他");
                        } else {
                            ToastUtil.showToast("由于对方的设置，你不能关注她");
                        }
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        }
    }

}
